package org.hamster.multidropbox.main.services
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.FileReference;
	import flash.net.FileReferenceList;
	
	import mx.collections.ArrayCollection;
	
	import org.hamster.common.puremvc.events.ParallelEvent;
	import org.hamster.common.puremvc.events.ParallelEventHandler;
	import org.osmf.elements.ParallelElement;
	
	[Event(name="complete", type="flash.events.Event")]

	public class AppFileBrowseService extends EventDispatcher
	{
		public static function newInstance():AppFileBrowseService
		{
			return new AppFileBrowseService();
		}
		
		private var fileReferenceList:FileReferenceList;
		private var parallelEventHandler:ParallelEventHandler;
		public var fileReferenceSuccessList:Array;
		public var fileReferenceFailureList:Array;
		
		public function browse():void
		{
			if (!fileReferenceList) {
				fileReferenceList = new FileReferenceList();
				fileReferenceList.addEventListener(Event.SELECT, fileReferenceListSelectHandler);
			}
			fileReferenceSuccessList = new Array();
			fileReferenceFailureList = new Array();
			
			fileReferenceList.browse();
		}
		
		protected function fileReferenceListSelectHandler(event:Event):void
		{
			fileReferenceList.removeEventListener(Event.SELECT, fileReferenceListSelectHandler);
			if (!parallelEventHandler) {
				parallelEventHandler = new ParallelEventHandler();
			}
			var fileReference:FileReference;
			for each (fileReference in fileReferenceList.fileList) {
				parallelEventHandler.addChild(fileReference, Event.COMPLETE, 
					[IOErrorEvent.IO_ERROR, SecurityErrorEvent.SECURITY_ERROR]);
			}
			
			parallelEventHandler.addEventListener(ParallelEvent.ALL_FINISHED, allFinishedHandler);
			parallelEventHandler.addEventListener(ParallelEvent.ITEM_FAILURE, itemFailureHandler);
			parallelEventHandler.addEventListener(ParallelEvent.ITEM_SUCCESS, itemSuccessHandler);
			
			for each (fileReference in fileReferenceList.fileList) {
				fileReference.load();
			}
		}
		
		protected function itemSuccessHandler(event:ParallelEvent):void
		{
			fileReferenceSuccessList.push(event.item.target);
		}
		protected function itemFailureHandler(event:ParallelEvent):void
		{
			fileReferenceFailureList.push(event.item.target);
		}
		
		protected function allFinishedHandler(event:ParallelEvent):void
		{
			this.dispatchEvent(new Event(Event.COMPLETE));
		}
		

	}
}